package com.yh.homestay.controller;

import com.yh.homestay.common.FastDFSUtil;
import com.yh.homestay.common.JsonUtils;
import com.yh.homestay.common.PictureResult;
import com.yh.homestay.utils.QiNiuUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
public class PictureController {
    /*@Autowired
    FastDFSUtil fastDFSUtil;

    @RequestMapping("/pic/upload")
    @ResponseBody
    public String picUpload(MultipartFile uploadFile) {
        PictureResult pictureResult = new PictureResult();
        try {
            String uploadPath = fastDFSUtil.uploadFile(uploadFile);
            String ss = uploadPath;
            String[] split = ss.split(":22122");
            String url = split[0] + split[1];
            System.out.println(split[0] + split[1]);
            pictureResult.setCode(0);
            pictureResult.setMsg("上传成功");
            Map map = new HashMap();
            map.put("src", url);
            pictureResult.setData(map);
            String json = JsonUtils.objectToJson(pictureResult);
            return json;
        } catch (IOException e) {
            e.printStackTrace();
            pictureResult.setCode(1);
            pictureResult.setMsg("上传失败");
            Map map = new HashMap();
            map.put("src", null);
            pictureResult.setData(map);
            String json = JsonUtils.objectToJson(pictureResult);
            return json;
        }
    }*/
    @RequestMapping(value = "/pic/upload",method = RequestMethod.POST)
    @ResponseBody
    public String picUpload(HttpServletRequest request,@RequestParam("uploadFile") MultipartFile uploadFile) throws IOException {
        FileInputStream fileInputStream = (FileInputStream) uploadFile.getInputStream();
        //生成随机名称
        String saveFileName = UUID.randomUUID().toString().replace("-", "");
        QiNiuUtil.upload2Qiniu(fileInputStream,saveFileName);
        PictureResult pictureResult = new PictureResult();
        pictureResult.setCode(0);
        pictureResult.setSrc(QiNiuUtil.qiniu_img_url_pre+saveFileName);
        String json = JsonUtils.objectToJson(pictureResult);
        return json;
    }
}
